package com.symone.crawler.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.symone.crawler.App;
import com.symone.crawler.action.Catcher;
import com.symone.crawler.config.CrawlerConfig;
import com.symone.crawler.data.ProxyData;
import com.symone.crawler.log.Log;
import com.symone.crawler.log.LogFactory;

import java.io.IOException;
import java.util.concurrent.ConcurrentMap;

public class ProxyService {
    private static Log logger = LogFactory.getLog(ProxyService.class);

    private volatile Catcher catcher = new Catcher();
    private String url;

    public ProxyService(String url){
        this.url = url;
    }

    public void saveWithFetch() {
        synchronized (this) {
            try {
                String result = catcher.catchDocument(CrawlerConfig.PROXY_URL + CrawlerConfig.PROXY_NUM,null).body();
                JSONArray proxyArray = JSONUtil.parseObj(result).getJSONArray("data");
                for (int j = 0; j < proxyArray.size(); j++) {
                    ProxyData data = new ProxyData();
                    data.setIp(proxyArray.getJSONObject(j).getStr("ip"));
                    data.setPort(proxyArray.getJSONObject(j).getInt("port"));
                    data.setExpireTime(proxyArray.getJSONObject(j).getDate("expire_time"));
                    data.setCity(proxyArray.getJSONObject(j).getStr("city"));
                    data.setIsp(proxyArray.getJSONObject(j).getStr("icp"));
                    App.PROXY_DATA_QUEUE.add(data);
                }
                CrawlerConfig.PROXY_NUM = 1;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static synchronized ProxyData getProxyData() throws InterruptedException {
        while (App.PROXY_DATA_QUEUE.take() == null){
            Thread.sleep(6000);
        }
        ProxyData proxyData = App.PROXY_DATA_QUEUE.take();
        App.PROXY_THREAD_MAP.put(Thread.currentThread().getId(),proxyData);
        return proxyData;
    }
}
